package com.jww.controller.store;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageInfo;
import com.jww.controller.BaseServlet;
import com.jww.domain.store.Course;
import com.jww.service.CourseService;
import com.jww.utils.BeanUtil;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@WebServlet("/store/course/*")
public class CourseServlet extends BaseServlet {

    //  查询所有
    private void findAll(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        String pageSize = req.getParameter("pageSize");
        String pageNum = req.getParameter("pageNum");

        List<Course> list = courseService.findAll(pageNum, pageSize);
        //  将数据交由分页插件处理获取分页信息
        PageInfo<Course> pageInfo = new PageInfo<>(list);
        //将结果传回来也就是存入作用域
        req.setAttribute("page", pageInfo);

        //页面跳转
        req.getRequestDispatcher("/pages/store/course/list.jsp").forward(req, resp);
    }

    /**
     * 新增操作
     *
     * @param req
     * @param resp
     * @throws Exception
     */
    private void save(HttpServletRequest req, HttpServletResponse resp) throws Exception {

        //获取页面数据封装到指定对象中去
        Course course = BeanUtil.fillBean(req, Course.class);
        courseService.save(course);
        //调用findAll方法
        findAll(req, resp);

    }

    /**
     * 批量删除
     *
     * @param req
     * @param resp
     * @throws Exception
     */
    private void deleteByIds(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        //获取批量删除的id
        String ids = req.getParameter("ids");
        // 调用service
        boolean flag = courseService.deleteByIds(ids);

        if (flag) {
            findAll(req, resp);
        } else {
            //跳转到错误页面
        }

    }

    /**
     * 根据id查询当前企业信息，并跳转到修改页面
     *
     * @param req
     * @param resp
     * @throws Exception
     */
    private void toUpdate(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        //获取当前id
        String id = req.getParameter("id");
        Course course = courseService.findById(id);
        req.setAttribute("course", course);
        req.getRequestDispatcher("/pages/store/course/update.jsp").forward(req, resp);

    }

    /**
     * 真的修改
     *
     * @param req
     * @param resp
     * @throws Exception
     */
    private void update(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        //获取修改页面表单提交的数据，并封装到Course对象
        Course course = BeanUtil.fillBean(req, Course.class);
        courseService.update(course);
        findAll(req, resp);

    }

}
